package hxy.dragon.location_record;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.MenuItem;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.PreferenceManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ejlchina.okhttps.OkHttps;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import hxy.dragon.location_record.tencent.LocationModel;

public class HistoryActivity extends AppCompatActivity {

    public static List<LocationModel> locationModelList = new ArrayList<>();
    public static LocationAdapter adapter;
    private int pageNum = 1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history);

        ActionBar actionBar = getSupportActionBar();  //这里的ActionBar实际上已经是通过ToolBar实现
        if (actionBar != null) {
            //Toolbar最左侧的按钮被称为HomeAsUp按钮，默认图标是返回箭头，作用就是返回上一个活动
            actionBar.setDisplayHomeAsUpEnabled(true);  //允许显示返回按钮
            actionBar.setTitle("历史记录");
        }

        RefreshLayout refreshLayout = (RefreshLayout) findViewById(R.id.refreshLayout);
        refreshLayout.setRefreshHeader(new ClassicsHeader(this));
        refreshLayout.setRefreshFooter(new ClassicsFooter(this));
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                locationModelList.clear();
                getDataFromServer(1, refreshlayout);
                refreshlayout.finishRefresh(20/*,false*/);//传入false表示刷新失败
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                pageNum++;
                getDataFromServer(pageNum, refreshlayout);
                refreshlayout.finishLoadMore();
//                refreshlayout.finishLoadMoreWithNoMoreData();//传入false表示加载失败
            }
        });


        androidx.recyclerview.widget.RecyclerView recyclerView = (androidx.recyclerview.widget.RecyclerView) findViewById(hxy.dragon.location_record.R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new LocationAdapter(this, locationModelList);
        recyclerView.setAdapter(adapter);
        locationModelList.clear();
        getDataFromServer(1, refreshLayout);
    }

    /**
     * 从服务器中获取数据
     */
    private void getDataFromServer(int pageNum, RefreshLayout refreshlayout) {
//        long userId = KVUtils.get().getLong(Constant.USER_ID);
        SharedPreferences defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        long userId = Long.parseLong(defaultSharedPreferences.getString("signature", "0"));
//        Toast.makeText(getBaseContext(), "请求数据" + userId, Toast.LENGTH_SHORT).show();
        OkHttps.async("/location")
                .addUrlPara("userId", userId)
                .addUrlPara("current", pageNum).setOnResponse(onResponse -> {
            int status1 = onResponse.getStatus();
            if (status1 == 200) {
                String response = onResponse.getBody().toString();
                JSONObject jsonObject = JSONObject.parseObject(response);
                JSONObject data1 = jsonObject.getJSONObject("data");
                JSONArray data = data1.getJSONArray("records");
                int size = data.size();
                if (size > 0) {
                    for (int i = 0; i < size; i++) {
                        JSONObject jsonObject1 = data.getJSONObject(i);
                        String address = jsonObject1.getString("address");
                        String name = jsonObject1.getString("name");
                        Long time = jsonObject1.getLong("time");
                        LocationModel locationModel = new LocationModel();
                        locationModel.setAddress(address);
                        locationModel.setName(name);
                        locationModel.setTime(time);
                        locationModelList.add(locationModel);
                    }
                    adapter.notifyDataSetChanged();
                    refreshlayout.finishLoadMore();
                } else {
                    refreshlayout.finishLoadMoreWithNoMoreData();
                }
            } else {
                refreshlayout.finishLoadMore(false);
            }
        }).setOnException(exception -> {
            String message = exception.getMessage();
        }).get();
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
